<?php

namespace app\common;

use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Sms\V20210111\SmsClient;
use TencentCloud\Sms\V20210111\Models\SendSmsRequest;
use think\facade\Db;

/**
 * 腾讯云短信类
 */
class Txsms
{
    private $config;

    public function __construct()
    {
        $config = Db::name('config_data')->where('config_id',9)->select()->toArray();
        $arr = [];
        foreach ($config as $k => $v) {
            if ($v['code'] != 'id') {
                $arr[$v['code']] = $v['value'];
            }
        }
        $this->config = $arr;
    }


    /**
     * 腾讯云发送短信
     */
    public function tx_sms($phone,$code){
        $config = $this->config;
        try {
            $cred = new Credential($config['SecretId'], $config['SecretKey']);
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("sms.tencentcloudapi.com");

            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $client = new SmsClient($cred, $config['region'], $clientProfile);

            $req = new SendSmsRequest();

            $params = array(
                "PhoneNumberSet" => [$phone],
                "SmsSdkAppId" => (string)$config['SmsSdkAppId'],
                "SignName" => (string)$config['SignName'],
                "TemplateId" => (string)$config['TemplateId'],
                "TemplateParamSet" => [(string)$code,"120"]
            );
            $req->fromJsonString(json_encode($params));

            $resp = $client->SendSms($req);
            return json_decode($resp->toJsonString())->SendStatusSet;
        }
        catch(TencentCloudSDKException $e) {
            return false;
        }
    }
}